/**
 * Description:
 * Class Name:conditionAccount
 * Date:2022/5/8 14:02
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程._16_6_线程间通信._16_6_2_使用Condition控制线程来通信;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class conditionAccount {
    // 显示定义Lock对象
    private final Lock lock = new ReentrantLock();
    // 获取指定Lock对象对应的Condition实例
    private final Condition condition = lock.newCondition();
    // 仍旧是封存账户编号、账户余额这两个成员变量
    private String accountNo;
    private double balance;
    // 标志账户中是否已有存款
    private boolean flag = false;
    public conditionAccount(){}
    public conditionAccount(String accountNo, double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }
    // 省略getter和setter，不给balance设置setter

    public String getAccountNo() {
        return accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        conditionAccount that = (conditionAccount) o;
        return that.getAccountNo().equals(getAccountNo());
    }

    @Override
    public int hashCode() {
        return accountNo.hashCode();
    }

    public void draw(double drawAmount){
        // 加锁
        lock.lock();
        try {
            // flag为假，表明未存钱
            if (!flag){
                condition.await();
            }
            else {
                // 执行取钱操作
                System.out.println(Thread.currentThread().getName() + " 取钱：" + drawAmount);
                balance -= drawAmount;
                System.out.println("账户余额为：" + balance);
                flag = false;
                // 唤醒其他线程
                condition.signalAll();
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        // 使用finally块来释放锁
        finally {
            lock.unlock();
        }
    }

    public void deposit(double depositAmount){
        // 加锁
        lock.lock();
        try {
            if (flag){
                condition.await();
            }
            else {
                System.out.println(Thread.currentThread().getName() + " 存钱：" + depositAmount);
                balance += depositAmount;
                System.out.println("余额为：" + balance);
                flag = true;
                condition.signalAll();
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
        // 使用finally块来释放锁
        finally {
            lock.unlock();
        }
    }
}
